﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SeleniumContextFactory.cs" company="">
//   
// </copyright>
// <summary>
//   The selenium context factory.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace UITest.Selenium.SeleniumContext
{
    using System;

    using UITest.Selenium.WebDrivers;

    /// <summary>
    ///     The selenium context factory.
    /// </summary>
    public class SeleniumContextFactory
    {
        #region Static Fields

        private static readonly SeleniumContextFactory Instance = new SeleniumContextFactory();

        #endregion

        #region Properties

        private SeleniumContext SeleniumContext { get; set; }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        ///     The dispose.
        /// </summary>
        public static void Dispose()
        {
            Instance.SeleniumCleanup();
        }

        /// <summary>
        ///     The get selenium context.
        /// </summary>
        /// <returns>
        ///     The <see cref="SeleniumContext" />.
        /// </returns>
        /// <exception cref="NullReferenceException">
        /// </exception>
        public static SeleniumContext GetSeleniumContext()
        {
            if (Instance.SeleniumContext == null)
            {
                throw new NullReferenceException("You MUST use SeleniumContextFactory.New() before calling this method");
            }

            return Instance.SeleniumContext;
        }

        /// <summary>
        /// The new.
        /// </summary>
        /// <param name="remoteWebDriverProvider">
        /// The remote Web Driver Provider.
        /// </param>
        public static void New(IRemoteWebDriverProvider remoteWebDriverProvider = null)
        {
            Instance.SeleniumCleanup();
            Instance.SeleniumContextInit(remoteWebDriverProvider);
        }

        #endregion

        #region Methods

        private void SeleniumCleanup()
        {
            if (this.SeleniumContext != null)
            {
                this.SeleniumContext.Dispose();
            }
        }

        private void SeleniumContextInit(IRemoteWebDriverProvider remoteWebDriverProvider = null)
        {
            if (this.SeleniumContext != null)
            {
                this.SeleniumContext.Dispose();
            }

            this.SeleniumContext = new SeleniumContext(remoteWebDriverProvider ?? new ChromeProvider());
        }

        #endregion
    }
}